import router from './router/index'
import store from './store'
import { ElMessage } from '@toms/element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from './router/index'

function redirectToLogin(next, to) {
    next(`/login?redirect=${to.path}`)
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/pass-design'] // no redirect whitelist

whiteList.push('/login')


router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoutes = store.getters.addRoutes.length > 0
      const hasUserInfo = store.getters.userInfo
      if (hasRoutes && hasUserInfo) {
        next()
      } else {
        try {          
          store.dispatch('app/setCountries')
          await store.dispatch('user/getInfo')
          const routes = await store.dispatch('permission/generateRoutes')
          routes.concat(asyncRoutes).forEach((route) => {
            console.log(route)
            router.addRoute(route)
          })

          router.addRoute({
            path: '/:pathMatch(.*)*',
            redirect: '/404',
            hidden: true
          })
          
          next({ ...to, replace: true })
          return
        } catch (error) {
          await store.dispatch('user/resetToken')
          ElMessage.error(error || 'Has Error')
          redirectToLogin(next, to)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      return next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      redirectToLogin(next, to)
      NProgress.done()
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
